/**
 * Created by kevin on 2017/6/1.
 */
var mongoose = require('mongoose');
mongoose.Promise = global.Promise;
let env = require("./utils/env");
var fs = require('fs');

var db = function () {
    
};

db.modelMaker = mongoose;

db.connectConfig = function (host,port,dbname,username,passwd,callback) {
    var content = 'mongodb://';
    if (username && passwd) {
        username = username.replace(/@/g,'%40');
        passwd = passwd.replace(/@/g,'%40');
        content += (username + ':' + passwd + '@');
    }
    content += host;
    if (port) {
        content += (':' + port);
    }
    content += ('/' + dbname);

    console.log(content);
    db.disconnect();
    mongoose.connect(content);
    var con = mongoose.connection;
    if (callback) {
        con.once('error', function (err) {
            console.log(err);
            callback(new Error('无法连接到数据库，请检查数据库配置'));
        });
        con.once('open',function (data) {
            console.log('已连接到数据库');
            callback(null);
        });
    }
};

db.connect = function (callback) {
    let host = process.env.dbhost || "localhost";
    let port = process.env.dbport || "27017";
    let name = process.env.dbname || "ipackk";
    let username = process.env.username;
    let password = process.env.password;

    db.connectConfig(host,port,name,username,password,callback);
};

db.disconnect = function () {
    if (mongoose.connection) {
        mongoose.disconnect(mongoose.connection);
    }
};
// mongoose.connect('mongodb://localhost/leopard');



module.exports = db;